package cl.whyem.beans.managedBeans2;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.validator.GenericValidator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cl.whyem.utils.TutorialesUtil;

@SuppressWarnings("serial")
@ManagedBean
@ViewScoped
public class SearchBrowserBean implements java.io.Serializable {

	private static Logger logger = LoggerFactory.getLogger(SearchBrowserBean.class); 
	
	private String searchString;
	private String searchEngine;

	public String doSearch() throws IOException {
		logger.info(">>> Buscar en buscador <<<");
		logger.info(">>> PARAMETRO <<< "+searchString);
		logger.info(">>> MOTOR <<< "+searchEngine);
		
		searchString = URLEncoder.encode(searchString, "utf-8");
		if(GenericValidator.isBlankOrNull(searchString) || GenericValidator.isBlankOrNull(searchEngine)) {
			return "error";
		}
		
		String searchURL = TutorialesUtil.makeURL(searchEngine, searchString);
		ExternalContext exContext = FacesContext.getCurrentInstance().getExternalContext();
		HttpServletResponse response = (HttpServletResponse) exContext.getResponse();
		response.sendRedirect(searchURL);
		return null;
	}
	
	public List<String> getSearchEnginesList() {
		return TutorialesUtil.getSearchEnginesStringList();
	}

	public String getSearchString() {
		return searchString;
	}

	public void setSearchString(String searchString) {
		this.searchString = searchString;
	}

	public String getSearchEngine() {
		return searchEngine;
	}

	public void setSearchEngine(String searchEngine) {
		this.searchEngine = searchEngine;
	}
	
	
}
